package com.springboot.thymeleaf.springbootthymeleaf.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.io.IOException;

/**
 * @Classname ${小柯}
 * @Description TODO
 * @Date 2019/10/18 19:40
 * @Created by Administrator
 */
public class JsonUtil {

    public JsonUtil(){

    }

    public static String toJson(Object bean) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        return objectMapper.writeValueAsString(bean);
    }

    public static <T> T fromJson(String json, Class valueType) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
       return (T) objectMapper.readValue(json, valueType);
    }

}
